<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-11-22 09:11:57
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-11-22 17:19:58
 * @FilePath: /nhw/src/components/AMap/index.vue
-->
<template>
  <div class="map-container">
    <div id="map"></div>
    <p class="amap-text" :style="{ left: left + 'px', top: top + 'px' }">
      {{ address }}
    </p>
    <div class="controls">
      <button class="cancel" @click="onCancel">取消</button>
      <button class="confirm" @click="onConfirm">确认</button>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import AMaptoBDMap from "@/utils/AMapToBDMap";
export default {
  name: "Map",

  data() {
    return {
      lng: "",
      lat: "",
      address: "",
      marker: null,
      left: 0,
      top: 0,
    };
  },

  mounted() {
    this.createMap();
  },

  methods: {
    async createMap() {
      const AMap = await AMapLoader.load({
        //注册开发者/创建应用，选择web端JS API（必须）
        key: "46e1d72f2060dc375ac04f10abfd8cdb", //首次load必填
        version: "1.4.15",
        plugins: ["AMap.Geolocation", "AMap.Geocoder", "AMap.ToolBar"],
      });

      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 100, //超过10秒后停止定位，默认：无穷大
        maximumAge: 0, //定位结果缓存0毫秒，默认：0
        buttonOffset: new AMap.Pixel(10, 20),
        zoomToAccuracy: true,
        buttonPosition: "RB",
      });

      geolocation.getCurrentPosition((status, result) => {
        if (status === "complete") {
          const { position, formattedAddress } = result;
          this.address = formattedAddress;
          this.lng = position.lng;
          this.lat = position.lat;
          this.renderMap(this.lng, this.lat);
        } else if (status === "error") {
          console.log("map:", status);
        }
      });
    },

    renderMap(lng, lat) {
      const map = new AMap.Map("map", {
        zoom: 15,
        center: [lng, lat],
        resizeEnable: true,
        viewMode: "2D",
      });
      //添加控制器
      const tool = new AMap.ToolBar({
        locate: true,
        // autoPosition: true, //加载时自动获取位置
        liteStyle: true,
      });
      map.addControl(tool);
      tool.on("location", (ev) => {
        this.setLabel(ev.lnglat);
        this.top = 0;
        this.left = 0;
      });
      //构建icon
      this.setMarker(map, { lng, lat });
      //构建text
      this.setLabel({ lng, lat });
      //添加点击选取位置事件
      map.on("click", (ev) => {
        const lnglat = ev.lnglat;
        const pixel = ev.pixel;
        this.left = pixel.x;
        this.top = pixel.y;
        this.setLabel(lnglat);
      });
    },
    setMarker(map, point) {
      // 创建一个 Marker 实例：
      this.marker = new AMap.Marker({
        // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        position: new AMap.LngLat(point.lng, point.lat),
      });
      // 将创建的点标记添加到已有的地图实例：
      map.add(this.marker);
    },
    setLabel(point) {
      const geocoder = new AMap.Geocoder({
        city: "全国",
      });
      const lnglat = [point.lng, point.lat];
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          // result为对应的地理位置详细信息
          console.log(result);
          this.address = result.regeocode.formattedAddress;
          this.marker && this.marker.setPosition(lnglat);
        }
      });
    },
    emitPoint() {
      const { lng, lat } = AMaptoBDMap(this.lng, this.lat);
      this.$emit("confirm", {
        lng,
        lat,
        address: this.address,
      });
    },
    onConfirm() {
      this.emitPoint();
    },
    onCancel() {
      this.$emit("cancel");
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@/style/var.less");
@import url("~@/style/mixin.less");
.map-container {
  height: 100%;
  position: relative;
  #map {
    height: 100%;
    width: 100%;
  }
  .controls {
    height: 10%;
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: center;
    .confirm {
      .clickableBtn();
      height: 78px;
      background: @primary;
      color: #fff;
      width: 20%;
      margin: 20px;
    }
    .cancel {
      .disabledBtn();
      height: 78px;
      width: 20%;
      margin: 20px;
    }
  }

  .amap-text {
    position: absolute;
    transition: all 0.5s;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    max-width: 50%;
    padding: 4px;
    border-radius: 4px;
    font-size: 18px;
  }
}
</style>